<template>
  <div>
    <van-index-bar :index-list="computedList">
      <div v-for="data in cityList" >
        <van-index-anchor :index="data.type" :key="data.type"/>
        <van-cell :title="item.name" v-for="item in data.list" :key="item.label"
        @click="handleClick(item)"
        />

      </div>
    </van-index-bar>
  </div>
</template>

<script>
import http from "@/util/http";
import Vue from 'vue';
import { IndexBar, IndexAnchor } from 'vant';

Vue.use(IndexBar);
Vue.use(IndexAnchor);
export default {
  name: 'city',
  data() {
    return {
      cityList: []
    }
  },
  computed:{
    //移除vant组件列表空数组   重制导航列表
    computedList(){
      return this.cityList.map(item => item.type)
    }
  },
  mounted() {
    http.get('/comments',{
    }).then(res =>{
      this.cityList = this.renderCity(res.data.data)
    })
  },
  methods: {
    renderCity(list) {
      var cityList = []
      var letterList = []
      for (var i = 65; i < 91; i++) {
        letterList.push(String.fromCharCode(i))
      }
      letterList.forEach(letter => {
        var newList = list.filter(item => {
          return item.pinyin.substring(0, 1).toUpperCase() === letter

        })
        //数组为空的则不进行push() 去除空数组
        newList.length > 0 && cityList.push({
          type: letter,
          list: newList
        })
      })

      return cityList

    },
    handleClick(item){
      // this.$store.state.cityName = item.name
      this.$store.commit('changeCityName',item.name)
      this.$router.back()
    }
  }
}
</script>

<style scoped>

</style>
